var usersDS = new Ext.data.JsonStore({
    storeId: "usersShare",
    url: "/addama-users/users",
    root: "users",
    fields: ["fullName", "emailAddress", "uri"],
    sortInfo: {
        field: "fullName",
        direction: "ASC"
    }
});

var groupDS = new Ext.data.JsonStore({
    storeId: "groupsShare",
    url: "/addama-groups/groups",
    root: "groups",
    fields: ["name", "description", "uri"],
    sortInfo: {
        field: "name",
        direction: "ASC"
    }
});

eventManager.registerNodeSelectListener(function(node) {
    initDataStores();

    var ownerUrl = node.attributes.uri + "/isOwner";
    Ext.Ajax.request({
        url: ownerUrl,
        method: "GET",
        params: {
            "user_uri": LoggedInUser.userUri
        },
        success: function(response) {
            var status = response.status;
            if (status == "200") {
                beginSharing(node);
            }
        },
        failure: function() {
            var ownerId = "";
            console.log("Not admin/owner of resource");
            Ext.getDom("sharing-manage-div").innerHTML = "";
            Ext.getDom("sharing-view-functions-div").innerHTML = "";
            Ext.getDom("sharing-view-existing-div").innerHTML = "";
            Ext.getDom("sharing-edit-functions-div").innerHTML = "";
            Ext.getDom("sharing-edit-existing-div").innerHTML = "";
            var getOwnerUrl = node.attributes.uri + "/owner";
            Ext.Ajax.request({
                url: getOwnerUrl,
                method: "GET",
                success: function(response) {
                    var usersDecoded = Ext.util.JSON.decode(response.responseText);
                    var userArray = getUserDetail(usersDecoded.owner);
                    ownerId = userArray[0];
                    new Ext.Panel({
                        id: "aclTabsId",
                        title: "Resource Owner:" + ownerId,
                        applyTo: "sharing-view-functions-div",
                        autoWidth:true,
                        autoHeight:true,
                        defaults:{autoHeight: true}//,
                        //html: "Owner is " + ownerId
                    });
                }
            });
        }
    });
});

function initDataStores() {
    usersDS.load();
    groupDS.load();
}

function processEveryone(node) {
    var path = '/addama-sharing/viewing' + node.attributes.uri;
    var ejson = {"everybody":true};
    Ext.Ajax.request({
        url: path,
        method: 'POST',
        params: {
            acl: Ext.encode(ejson)
        },
        success: function() {
            eventManager.fireStatusMessageEvent({text: "Allow Everyone View Permission set for " + node.attributes.name, level: "info"});
            beginSharing(node);
        },
        failure: function() {
            eventManager.fireStatusMessageEvent({text: "Allow Everyone View Permission failed for " + node.attributes.name, level: "error"});
        }
    });
}

function processViewUsers(node) {
    var cview = true;
    var cedit = false;
    var cowner = false;
    var usersPanel = getUsersPanelSharing(cview, cedit, cowner, node);
    var win = new Ext.Window({
        title: "Select User(s)",
        id: "sharingViewUserId",
        closable: true,
        modal: true,
        width: 400,
        autoHeight: true,
        items: [usersPanel]
    });
    win.show();
}

function processViewGroups(node) {
    var cview = true;
    var cedit = false;
    var groupsPanel = getGroupsPanelSharing(cview, cedit, node);
    var win = new Ext.Window({
        title: "Select Group(s)",
        id: "sharingViewGroupId",
        closable: true,
        modal: true,
        width: 400,
        autoHeight: true,
        items: [groupsPanel]
    });
    win.show();
}

function processEditUsers(node) {
    var cview = false;
    var cedit = true;
    var cowner = false;
    var usersPanel = getUsersPanelSharing(cview, cedit, cowner, node);
    var win = new Ext.Window({
        title: "Select User(s)",
        id: "sharingEditUserId",
        closable: true,
        modal: true,
        width: 400,
        autoHeight: true,
        items: [usersPanel]
    });
    win.show();
}

function processEditGroups(node) {
    var cview = false;
    var cedit = true;
    var groupsPanel = getGroupsPanelSharing(cview, cedit, node);
    var win = new Ext.Window({
        title: "Select Group(s)",
        id: "sharingEditGroupId",
        closable: true,
        modal: true,
        width: 400,
        autoHeight: true,
        items: [groupsPanel]
    });
    win.show();
}

function sharing(node, jsonObj) {
    var everybody = false;
    var doNotReset = false;
    var viewUsers = null;
    var viewGroups = null;
    if (jsonObj) {
        everybody = jsonObj.everybody;
        viewUsers = jsonObj.users;
        viewGroups = jsonObj.groups;
    }
    Ext.getDom("sharing-view-functions-div").innerHTML = "";
    Ext.getDom("sharing-manage-div").innerHTML = "";

    var everyoneInfo = "Everyone can view";
    var viewUsersHtml = "";
    var viewGroupsHtml = "";

    var userViewEnabled = true;
    var groupViewEnabled = true;
    var everyoneEnabled = true;

    if (!everybody) {
        everyoneInfo = "";
        userViewEnabled = false;
        groupViewEnabled = false;
        everyoneEnabled = false;
    }
    var everyoneViewButton = new Ext.Button({
        id: "allowEveryoneViewButtonId",
        text: "Allow Everyone",
        disabled: everyoneEnabled,
        handler: function() {
            processEveryone(node);
        }
    });
    var userViewButton = new Ext.Button({
        id: "addUserViewButtonId",
        text: "Add User",
        disabled: userViewEnabled,
        handler: function() {
            processViewUsers(node);
        }
    });
    var groupViewButton = new Ext.Button({
        id: "addGroupViewButtonId",
        text: "Add Group",
        disabled: groupViewEnabled,
        handler: function() {
            processViewGroups(node);
        }
    });
    var removeSharingHtml = "";
    if (!everybody && !viewUsers && !viewGroups) {
        removeSharingHtml = "<b>Currently not shared</b>";
        doNotReset = true;
    }
    var stopSharingButton = new Ext.Button({
        id: "stopSharingButtonId",
        text: "Stop Sharing",
        disabled: doNotReset,
        handler: function() {
            resetSharing(node);
        }
    });
    var changeOwnerButton = new Ext.Button({
        id: "changeOwnerButtonId",
        text: "Change Owner",
        disabled: false,
        handler: function() {
            changeOwner(node);
        }
    });
    var ownerId = "";
    var getOwnerUrl = node.attributes.uri + "/owner";
    Ext.Ajax.request({
        url: getOwnerUrl,
        method: "GET",
        success: function(response) {
            var usersDecoded = Ext.util.JSON.decode(response.responseText);
            var userArray = getUserDetail(usersDecoded.owner);
            ownerId = userArray[0];
            Ext.getDom("sharing-view-functions-div").innerHTML = "";
            Ext.getDom("sharing-manage-div").innerHTML = "";
            new Ext.Panel({
                id: "sharingManagePanelId",
                title: "Resource Owner: " + ownerId,
                applyTo: "sharing-manage-div",
                autoWidth:true,
                autoHeight:true,
                defaults:{autoHeight: true},
                html: removeSharingHtml,
                bbar: [stopSharingButton, changeOwnerButton]
            });
            new Ext.Panel({
                id: "everyOnePanelId",
                title: "Viewing Permissions",
                applyTo: "sharing-view-functions-div",
                autoWidth:true,
                autoHeight:true,
                defaults:{autoHeight: true},
                html: everyoneInfo,
                bbar: [everyoneViewButton, userViewButton, groupViewButton]
            });
            loadCurrentViewUserGroupsPanel(viewUsers, viewGroups, node);
        },
        failure: function() {
            eventManager.fireStatusMessageEvent({text: "Failed on checking owner", level: "error"});
        }
    });
    return true;
}

function sharingEdit(node, jsonObj) {

    var editUsers = null;
    var editGroups = null;
    if (jsonObj) {
        editUsers = jsonObj.users;
        editGroups = jsonObj.groups;
    }
    Ext.getDom("sharing-edit-functions-div").innerHTML = "";
    var editUsersHtml = "";
    var editGroupsHtml = "";
    var userEditButton = null;
    var groupEditButton = null;
    userEditButton = new Ext.Button({
        id: "addUserEditButtonId",
        text: "Add User",
        disabled: false,
        handler: function() {
            processEditUsers(node);
        }
    });
    groupEditButton = new Ext.Button({
        id: "addGroupEditButtonId",
        text: "Add Group",
        disabled: false,
        handler: function() {
            processEditGroups(node);
        }
    });

    new Ext.Panel({
        id: "editPanelId",
        title: "Editing Permissions",
        applyTo: "sharing-edit-functions-div",
        autoWidth:true,
        autoHeight:true,
        defaults:{autoHeight: true},
        tbar: [userEditButton, groupEditButton]
    });

    loadCurrentEditUserGroupsPanel(node, editUsers, editGroups);
    return true;
}

function loadCurrentViewUserGroupsPanel(users, groups, node) {
    Ext.getDom("sharing-view-existing-div").innerHTML = "";
    if (users != null || groups != null) {
        var myArray = new Array();
        if (users != null) {
            for (i = 0; i < users.length; i++) {
                myArray[i] = getUserDetail(users[i]);
            }
        }
        var length = myArray.length;
        if (groups != null) {
            for (i = 0; i < groups.length; i++) {
                myArray[length + i] = getGroupDetail(groups[i]);
            }
        }
        var myStore = new Ext.data.ArrayStore({
            fields: ['key', "desc"],
            data: myArray
        });
        var panel = new Ext.grid.GridPanel({
            id: "currentUsersGroupsSharingGridId",
            applyTo: "sharing-view-existing-div",
            store: myStore,
            layout: 'fit',
            autoExpandColumn: 'key',
            columns: [
                {
                    id: "key",
                    header: "Name",
                    sortable: true,
                    width: 120,
                    autoScroll: true,
                    dataIndex: "key"
                },
                {
                    id: "desc",
                    header: "Email/Info",
                    width: 120,
                    sortable: true,
                    autoScroll: true,
                    dataIndex: "desc"
                }
            ],
            viewConfig: {autoScroll: true, forceFit: true},
            sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
            stripeRows: true,
            autoWidth: true,
            autoHeight: true,
            border: true,
            tbar: [
                new Ext.Button({
                    id: "removeSharingButton",
                    text: "Remove Selected",
                    disabled: true,
                    handler: function() {
                        onRemoveSharingSelected(node, users, groups);
                    }
                })
            ],
            listeners: {
                rowclick: onRemoveSelectSharing
            }
        });
    }
}

function loadCurrentEditUserGroupsPanel(node, users, groups) {
    Ext.getDom("sharing-edit-existing-div").innerHTML = "";
    if (users != null || groups != null) {
        var myArray = new Array();
        if (users != null) {
            for (i = 0; i < users.length; i++) {
                myArray[i] = getUserDetail(users[i]);
            }
        }
        var length = myArray.length;
        if (groups != null) {
            for (i = 0; i < groups.length; i++) {
                myArray[length + i] = getGroupDetail(groups[i]);
            }
        }
        var myStore = new Ext.data.ArrayStore({
            fields: ['key', "desc"],
            data: myArray
        });
        var panel = new Ext.grid.GridPanel({
            id: "currentUsersGroupsSharingEditGridId",
            applyTo: "sharing-edit-existing-div",
            store: myStore,
            layout: 'fit',
            autoExpandColumn: 'key',
            columns: [
                {
                    id: "key",
                    header: "Name",
                    sortable: true,
                    width: 120,
                    autoScroll: true,
                    dataIndex: "key"
                },
                {
                    id: "desc",
                    header: "Email/Info",
                    width: 120,
                    sortable: true,
                    autoScroll: true,
                    dataIndex: "desc"
                }
            ],
            viewConfig: {autoScroll: true, forceFit: true},
            sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
            stripeRows: true,
            autoWidth: true,
            autoHeight: true,
            border: true,
            tbar: [
                new Ext.Button({
                    id: "removeSharingEditButton",
                    text: "Remove Selected",
                    disabled: true,
                    handler: function() {
                        onRemoveSharingSelectedEdit(node, users, groups);
                    }
                })
            ],
            listeners: {
                rowclick: onRemoveSelectSharingEdit
            }
        });
    }
}

function onRemoveSelectSharing() {
    Ext.getCmp("removeSharingButton").enable();
}

function onRemoveSelectSharingEdit() {
    Ext.getCmp("removeSharingEditButton").enable();
}

function onRemoveSharingSelected(node, users, groups) {
    var grid = Ext.getCmp("currentUsersGroupsSharingGridId");
    var record = grid.getSelectionModel().getSelected();
    var selectedKey = record.data.desc;
    selectedKey = "/addama-users/users/" + selectedKey;
    var newUserList = new Array();
    var nu = 0;
    for (i = 0; i < users.length; i++) {
        if (selectedKey != users[i]) {
            newUserList[nu] = users[i];
            nu = nu + 1;
        }
    }
    var newGroupList = new Array();
    selectedKey = record.data.key;

    selectedKey = "/addama-groups/groups/" + selectedKey;
    var ng = 0;
    for (i = 0; i < groups.length; i++) {
        if (selectedKey != groups[i]) {
            newGroupList[ng] = groups[i];
            ng = ng + 1;
        }
    }
    var userGroupJson = {users: newUserList, groups:newGroupList};
    Ext.Ajax.request({
        url: '/addama-sharing/viewing' + node.attributes.uri,
        method: "POST",
        params: {
            acl: Ext.encode(userGroupJson)
        },
        success: function(response) {
            eventManager.fireStatusMessageEvent({text: "Remove of selected user/group successful", level: "info"});
            beginSharing(node);
        },
        failure: function(response) {
            eventManager.fireStatusMessageEvent({text: "System error on remove", level: "error"});
        }
    });
}

function onRemoveSharingSelectedEdit(node, users, groups) {
    var grid = Ext.getCmp("currentUsersGroupsSharingEditGridId");
    var record = grid.getSelectionModel().getSelected();
    var selectedKey = record.data.desc;
    selectedKey = "/addama-users/users/" + selectedKey;
    var newUserList = new Array();
    var nu = 0;
    for (i = 0; i < users.length; i++) {
        if (selectedKey != users[i]) {
            newUserList[nu] = users[i];
            nu = nu + 1;
        }
    }
    var newGroupList = new Array();
    selectedKey = record.data.key;
    selectedKey = "/addama-groups/groups/" + selectedKey;
    var ng = 0;
    for (i = 0; i < groups.length; i++) {
        if (selectedKey != groups[i]) {
            newGroupList[ng] = groups[i];
            ng = ng + 1;
        }
    }
    var userGroupJson = {users: newUserList, groups:newGroupList};
    Ext.Ajax.request({
        url: '/addama-sharing/editing' + node.attributes.uri,
        method: "POST",
        params: {
            acl: Ext.encode(userGroupJson)
        },
        success: function(response) {
            eventManager.fireStatusMessageEvent({text: "Remove of selected user/group from Edit successful", level: "info"});
            beginSharing(node);
        },
        failure: function(response) {
            eventManager.fireStatusMessageEvent({text: "System error on remove user/group from Edit", level: "error"});
        }
    });
}

function getUserDetail(userUri) {
    var splitted = userUri.split("/");
    var emailId = splitted[splitted.length - 1];
    var userDetailArray = [2];
    var index = usersDS.find("emailAddress", emailId);
    var record = usersDS.getAt(index);
    userDetailArray[0] = record.data.fullName;
    userDetailArray[1] = emailId;
    return userDetailArray;
}

function getGroupDetail(groupUri) {
    var splitted = groupUri.split("/");
    var groupId = splitted[splitted.length - 1];
    var groupDetailArray = [2];
    var index = groupDS.find("name", groupId);
    var record = groupDS.getAt(index);
    groupDetailArray[0] = groupId;
    groupDetailArray[1] = record.data.description;
    return groupDetailArray;
}

function beginSharing(node) {
    beginSharingView(node);
    beginSharingEdit(node);
}

function beginSharingView(node) {
    var path = '/addama-sharing/viewing' + node.attributes.uri;
    Ext.Ajax.request({
        url:    path,
        method: 'GET',
        success: function(response) {
            var responseJson = Ext.decode(response.responseText);
            sharing(node, responseJson);
        },
        failure: function() {
            //callback("undefined");
            eventManager.fireStatusMessageEvent({text: "Failed on loading sharing viewing for resource:" + node.attributes.name, level: "error"});
        }
    });
}


function beginSharingEdit(node) {
    var path = '/addama-sharing/editing' + node.attributes.uri;
    Ext.Ajax.request({
        url:    path,
        method: 'GET',
        success: function(response) {
            var responseJson = Ext.decode(response.responseText);
            sharingEdit(node, responseJson);
        },
        failure: function() {
            eventManager.fireStatusMessageEvent({text: "Failed on loading sharing editing for resource:" + node.attributes.name, level: "error"});
        }
    });
}

function onGrantUsersView(node) {
    var grid = Ext.getCmp("usersSharingViewGridId");
    var winId = "sharingViewUserId";
    if (grid.getSelectionModel().getSelected()) {
        var records = grid.getSelectionModel().getSelections();
        addUsersView(records, node, function() {
            eventManager.fireStatusMessageEvent({text: "User View Grant successful" , level: "info"});
            Ext.getCmp(winId).close();
            beginSharing(node);
        });
    }
}

function onGrantGroupsView(node) {
    var grid = Ext.getCmp("groupsGridSharing");
    var winId = "sharingViewGroupId";
    if (grid.getSelectionModel().getSelected()) {
        var records = grid.getSelectionModel().getSelections();
        addGroupsView(records, node, function() {
            eventManager.fireStatusMessageEvent({text: "Group Grant View successful" , level: "info"});
            Ext.getCmp(winId).close();
            beginSharing(node);
        });
    }
}

function onGrantUsersEdit(node) {
    var grid = Ext.getCmp("usersSharingEditGridId");
    var winId = "sharingEditUserId";
    if (grid.getSelectionModel().getSelected()) {
        var records = grid.getSelectionModel().getSelections();
        addUsersEdit(records, node, function() {
            eventManager.fireStatusMessageEvent({text: "User Edit Grant successful" , level: "info"});
            Ext.getCmp(winId).close();
            beginSharing(node);
        });
    }
}

function onGrantGroupsEdit(node) {
    var grid = Ext.getCmp("groupsGridSharingEdit");
    var winId = "sharingEditGroupId";
    if (grid.getSelectionModel().getSelected()) {
        var records = grid.getSelectionModel().getSelections();
        addGroupsEdit(records, node, function() {
            eventManager.fireStatusMessageEvent({text: "Group Grant View successful" , level: "info"});
            Ext.getCmp(winId).close();
            beginSharing(node);
        });
    }
}

function onUpdateOwner(node) {
    var grid = Ext.getCmp("updateOwnerGridId");
    var winId = "sharingChangeOwnerId";
    var record = grid.getSelectionModel().getSelected();
    var actorUri = "/addama-users/users/" + record.data.emailAddress;
    var path = node.attributes.uri + "/owner";
    Ext.Ajax.request({
        url: path,
        method: 'POST',
        params: {
            user_uri: actorUri
        },
        success: function(response) {
            eventManager.fireStatusMessageEvent({text: "Ownership update successful" , level: "info"});
            Ext.getCmp(winId).close();
            beginSharing(node);
        },
        failure: function() {
            eventManager.fireStatusMessageEvent({text: "System error on updating owner" , level: "error"});
        }
    });
}

function addUsersView(records, node, callOnSuccess) {
    var path = '/addama-sharing/viewing' + node.attributes.uri;
    var userList = [records.length];
    for (i = 0; i < records.length; i++) {
        var actorUri = "/addama-users/users/" + records[i].data.emailAddress;
        userList[i] = actorUri;
    }
    Ext.Ajax.request({
        url: path,
        method: 'POST',
        params: {
            acl: Ext.encode({users: userList, append: true})
        },
        success: function(response) {
            eventManager.fireStatusMessageEvent({text: "Selected users granted viewing privileges" , level: "info"});
            callOnSuccess();
        },
        failure: function() {
            eventManager.fireStatusMessageEvent({text: "An error occurred while adding users to view" , level: "error"});
        }
    });
}

function addUsersEdit(records, node, callOnSuccess) {
    var path = '/addama-sharing/editing' + node.attributes.uri;
    var userList = [records.length];
    for (i = 0; i < records.length; i++) {
        var actorUri = "/addama-users/users/" + records[i].data.emailAddress;
        userList[i] = actorUri;
    }
    Ext.Ajax.request({
        url: path,
        method: 'POST',
        params: {
            acl: Ext.encode({users: userList, append: true})
        },
        success: function(response) {
            eventManager.fireStatusMessageEvent({text: "Selected users granted editing privileges" , level: "info"});
            callOnSuccess();
        },
        failure: function() {
            eventManager.fireStatusMessageEvent({text: "An error occurred while adding users to edit" , level: "error"});
        }
    });
}

function onManageUserSelectSharing() {
    Ext.getCmp("updateUserSharingButton").enable();
    Ext.getCmp("removeUserSharingButton").enable();
}

function onUserSelectSharing(view, edit, owner) {

    if (view) {
        Ext.getCmp("addUsersViewButton").enable();
    } else if (edit) {
        Ext.getCmp("addUsersEditButton").enable();
    } else if (owner) {
        Ext.getCmp("updateOwnerButton").enable();
    }

}

function onGroupsSelectSharing(view, edit) {
    if (view) {
        Ext.getCmp("addGroupSharingButton").enable();
    } else if (edit) {
        Ext.getCmp("addGroupSharingEditButton").enable();
    }
}


function addGroupsView(records, node, callOnSuccess) {
    var path = '/addama-sharing/viewing' + node.attributes.uri;
    var groupsList = [records.length];
    for (i = 0; i < records.length; i++) {
        var groupUri = "/addama-groups/groups/" + records[i].data.name;
        groupsList[i] = groupUri;
    }
    Ext.Ajax.request({
        url: path,
        method: 'POST',
        params: {
            acl: Ext.encode({groups: groupsList, append: true})
        },
        success: function(response) {
            eventManager.fireStatusMessageEvent({text: "Selected groups granted viewing privileges" , level: "info"});
            callOnSuccess();
        },
        failure: function() {
            eventManager.fireStatusMessageEvent({text: "An error occurred while adding groups to viewing collaborators.", level: "info"});
        }
    });
}

function addGroupsEdit(records, node, callOnSuccess) {
    var path = '/addama-sharing/editing' + node.attributes.uri;
    var groupsList = [records.length];
    for (i = 0; i < records.length; i++) {
        var groupUri = "/addama-groups/groups/" + records[i].data.name;
        groupsList[i] = groupUri;
    }
    Ext.Ajax.request({
        url: path,
        method: 'POST',
        params: {
            acl: Ext.encode({groups: groupsList, append: true})
        },
        success: function(response) {
            eventManager.fireStatusMessageEvent({text: "Selected groups granted editing privileges" , level: "info"});
            callOnSuccess();
        },
        failure: function() {
            eventManager.fireStatusMessageEvent({text: "An error occurred while adding groups to editing collaborators.", level: "info"});
        }
    });
}

function resetSharing(node)
{
    Ext.MessageBox.confirm('Message', 'Stop sharing ' + node.attributes.name + '?', function(btn) {
        if (btn == 'yes') {
            var path = "/addama-sharing/stop" + node.attributes.uri;
            Ext.Ajax.request({
                url: path,
                method: "POST",
                success: function() {
                    eventManager.fireStatusMessageEvent({text: "No longer sharing", level: "info"});
                    beginSharing(node);
                },
                failure: function() {
                    eventManager.fireStatusMessageEvent({text: "Stop sharing failed", level: "error"});
                    return false;
                }
            });
            return true;
        }
    });
}

function changeOwner(node) {
    var cview = false;
    var cedit = false;
    var cowner = true;
    settingViewOnly = false;
    var usersPanel = getUsersPanelSharing(cview, cedit, cowner, node);
    var win = new Ext.Window({
        title: "Select User",
        id: "sharingChangeOwnerId",
        closable: true,
        modal: true,
        width: 400,
        autoHeight: true,
        items: [usersPanel]
    });
    win.show();
}

function getUsersPanelSharing(view, edit, owner, node) {
    var gridId = "usersSharingViewGridId";
    var singleSelect = false;
    var button = new Ext.Button({
        id: "addUsersViewButton",
        text: "Add",
        disabled: true,
        handler: function() {
            onGrantUsersView(node);
        }
    });
    if (edit) {
        gridId = "usersSharingEditGridId";
        button = new Ext.Button({
            id: "addUsersEditButton",
            text: "Add",
            disabled: true,
            handler: function() {
                onGrantUsersEdit(node);
            }
        })
    } else if (owner) {
        singleSelect = true;
        gridId = "updateOwnerGridId";
        button = new Ext.Button({
            id: "updateOwnerButton",
            text: "Change",
            disabled: true,
            handler: function() {
                onUpdateOwner(node);
            }
        })
    }
    var usersPanel = new Ext.Panel({
        width: 700,
        height: 500,
        border: true,
        items: [
            new Ext.grid.GridPanel({
                id: gridId,
                title: "Select Users",
                store: usersDS,
                columns: [
                    {
                        id: "fullName",
                        header: "Name",
                        sortable: true,
                        dataIndex: "fullName"
                    },{
                    id: "emailAddress",
                    header: "Email",
                    sortable: true,
                    dataIndex: "emailAddress"
                }
                ],
                viewConfig: {
                    forceFit: true
                },
                sm: new Ext.grid.RowSelectionModel({singleSelect: singleSelect}),
                stripeRows: true,
                height: 500,
                autoWidth: true,
                border: false,
                tbar: [button],
                listeners: {
                    rowclick: function() {
                        onUserSelectSharing(view, edit, owner);
                    }
                }
            })
        ]
    });
    return usersPanel;
}

function getGroupsPanelSharing(view, edit, node) {
    var gridId = "groupsGridSharing";
    var singleSelect = false;
    var button = new Ext.Button({
        id: "addGroupSharingButton",
        text: "Add",
        disabled: true,
        handler: function() {
            onGrantGroupsView(node);
        }
    });
    if (edit) {
        gridId = "groupsGridSharingEdit";
        button = new Ext.Button({
            id: "addGroupSharingEditButton",
            text: "Add",
            disabled: true,
            handler: function() {
                onGrantGroupsEdit(node);
            }
        })
    }
    var groupsPanel = new Ext.Panel({
        width: 700,
        height: 500,
        border: true,
        items: [
            new Ext.grid.GridPanel({
                id: gridId,
                title: "Groups",
                store: groupDS,
                columns: [
                    {
                        id: "name",
                        header: "Group",
                        sortable: true,
                        dataIndex: "name"
                    },
                    {
                        id: "description",
                        header: "Description",
                        sortable: true,
                        dataIndex: "description"
                    }
                ],
                viewConfig: {
                    forceFit: true
                },
                sm: new Ext.grid.RowSelectionModel(),
                stripeRows: true,
                height: 500,
                autoWidth: true,
                border: false,
                tbar: [ button
                ],
                listeners: {
                    rowclick: function () {
                        onGroupsSelectSharing(view, edit);
                    }
                }
            })
        ]
    });
    return groupsPanel;
}